var productCode;
var levelList;

$(function(){
    productCode = request("productCode");
    queryDicVipgrade();
    getDiyProduct();
});


/**
 * 配置参数显示.
 * @param obj
 */
function configParamDiy(obj) {
    if ('web' == obj.value) {
        if (obj.checked) {
            $('#ftpCheckbox').get(0).checked = true;
            $('#ftpConfig').css('display', '');
            $('#ftpPrice').css('display', 'none');
        } else {
            $('#ftpPrice').css('display', '');
        }
    }
    if ('ftp' == obj.value) {
        if (!obj.checked && $('#webCheckbox').get(0).checked) {
            $('#ftpCheckbox').get(0).checked = true;
            return true;
        } else {
            $('#ftpPrice').css('display', '');
        }
    }
    $('#' + obj.value + 'Config').css('display', obj.checked ? '' : 'none');
    $('#' + obj.value + 'Price').css('display', obj.checked ? '' : 'none');
    $('#ftpServerListArea').css('display', $('#webCheckbox').get(0).checked ? 'none' : '');

}

//获取会员等级
function queryDicVipgrade(){
    var service = {};
    var fn="queryVipgradeList";
    service = Commonjs.jsonToString(service);
    var params = Commonjs.getParams(fn,service);//获取参数
    var data=Commonjs.ajax(weburl,params,false);
    if(data.result == "success"){
        if(data.data==null)
            return;

        var html='';
        if (data.data.length>0){
            levelList=data.data;
            //购买
            html+='<tr><td>购买价格</td>';
            html+='<td colspan="14">根据第一月计算2至';
            html+='<select id="sel_reg" style="height:30px;">';
            html+='<option value="2">2</option>';
            html+='<option value="3">3</option>';
            html+='<option value="4">4</option>';
            html+='<option value="5">5</option>';
            html+='<option value="6">6</option>';
            html+='<option value="7">7</option>';
            html+='<option value="8">8</option>';
            html+='<option value="9">9</option>';
            html+='<option value="10">10</option>';
            html+='<option value="11">11</option>';
            html+='</select>月的价格';
            html+='<input type="button" class="btn btn-primary" onClick="calcPrice(\'reg\')" value="开始计算">';
            html+='<input type="button" class="btn btn-primary" onClick="clearPrice(\'reg\')" value="全部清空">';
            html+='</td></tr>';
            BaseForeach(data.data,function(i,item){
                html+='<tr>';
                html+='<td>'+item.levelName+'</td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_1_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_2_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_3_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_4_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_5_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_6_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_7_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_8_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_9_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_10_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_m_11_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_y_1_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_y_2_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_reg_y_3_'+item.levelCode+'" /></td>';
                html+='</tr>';
            });

            //续费
            html+='<tr><td>续费价格</td>';
            html+='<td colspan="14">根据第一月计算2至';
            html+='<select id="sel_renew" style="height:30px;">';
            html+='<option value="2">2</option>';
            html+='<option value="3">3</option>';
            html+='<option value="4">4</option>';
            html+='<option value="5">5</option>';
            html+='<option value="6">6</option>';
            html+='<option value="7">7</option>';
            html+='<option value="8">8</option>';
            html+='<option value="9">9</option>';
            html+='<option value="10">10</option>';
            html+='<option value="11">11</option>';
            html+='</select>月的价格';
            html+='<input type="button" class="btn btn-primary" onClick="calcPrice(\'renew\')" value="开始计算">';
            html+='<input type="button" class="btn btn-primary" onClick="clearPrice(\'renew\')" value="全部清空">';
            html+='<input type="button" class="btn btn-primary" onClick="getRegPrice()" value="取购买价格">';
            html+='</td></tr>';
            BaseForeach(data.data,function(i,item){
                html+='<tr>';
                html+='<td>'+item.levelName+'</td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_1_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_2_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_3_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_4_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_5_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_6_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_7_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_8_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_9_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_10_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_m_11_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_y_1_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_y_2_'+item.levelCode+'" /></td>';
                html+='<td><input type="text" class="input_txt" id="txt_renew_y_3_'+item.levelCode+'" /></td>';
                html+='</tr>';
            });
        }
        $('#tbody').append(html);
    }
}


function calcPrice(type){
    var year=parseInt($("#sel_"+type).val());
    for(var i=1;i<=year;i++){
        BaseForeach(levelList,function(j,item){
            var firstYear=$("#txt_"+type+"_m_1_"+item.levelCode).val();
            if(isNotNull(firstYear)){
                firstYear=parseFloat(firstYear);
                $("#txt_"+type+"_m_"+i+"_"+item.levelCode).val(firstYear*i);
            }
        });
    }
}

function clearPrice(type){
    var dialog=	art.dialog({
        lock : true,
        opacity : 0.4,
        width : 250,
        title : '提示',
        content : '您确定清空吗？',
        ok : function() {
            for(var i=1;i<=11;i++){
                BaseForeach(levelList,function(j,item){
                    $("#txt_"+type+"_m_"+i+"_"+item.levelCode).val("");
                });
            }
            for(var i=1;i<=3;i++){
                BaseForeach(levelList,function(j,item){
                    $("#txt_"+type+"_y_"+i+"_"+item.levelCode).val("");
                });
            }
        },cancel: function(){
            $('#dialog').hide();
        }
    });
}

function getRegPrice(){
    for(var i=1;i<=11;i++){
        BaseForeach(levelList,function(j,item){
            var regPrice=$("#txt_reg_m_"+i+"_"+item.levelCode).val();
            $("#txt_renew_m_"+i+"_"+item.levelCode).val(regPrice);
        });
    }
    for(var i=1;i<=3;i++){
        BaseForeach(levelList,function(j,item){
            var regPrice=$("#txt_reg_y_"+i+"_"+item.levelCode).val();
            $("#txt_renew_y_"+i+"_"+item.levelCode).val(regPrice);
        });
    }
}

//获取产品信息
function getDiyProduct(){
    var service = {};
    service.productCode = productCode;
    service.productClass = "diy";
    var fn="getProductPublic";
    service = Commonjs.jsonToString(service);
    var params = Commonjs.getParams(fn,service);//获取参数
    var result=Commonjs.ajax(weburl,params,false);
    if(result.result == "success"){
        //console.log(result);
        var obj=result.data.productView;
        $("#hidProductClass").val(obj.productClass);
        $("#productClassName").html(obj.productClassName);
        $('#subClassName').html(obj.subClassName);
        $("#hidProductCode").val(obj.productCode);
        $("#productCode").html(obj.productCode);
        $("#productName").val(obj.productName);
        $("#productDetail").val(obj.productDetail);
        //设置选中
        $("#status").find("option[value='"+obj.status+"']").attr("selected",true);

        //产品参数
        var productParam = obj.productParam;

        //数量
        $('#buyMaxNum').val(productParam.buyMaxNum);

        //价格配置
        $('#price').val(productParam.price);


        //element-ui param set
        vmDiyProduct.form.productName = obj.productName;

        vmDiyProduct.form.iconShow = productParam.iconShow ? productParam.iconShow : vmDiyProduct.form.iconShow;
        vmDiyProduct.form.iconUrl = productParam.iconUrl ? productParam.iconUrl : vmDiyProduct.form.iconUrl;
        vmDiyProduct.form.iconWidth = productParam.iconWidth ? productParam.iconWidth : vmDiyProduct.form.iconWidth ;
        vmDiyProduct.form.iconHeight = productParam.iconHeight ? productParam.iconHeight : vmDiyProduct.form.iconHeight;
        vmDiyProduct.form.iconLocal = productParam.iconLocal ? productParam.iconLocal : vmDiyProduct.form.iconLocal;
        vmDiyProduct.form.description = productParam.description ? productParam.description : vmDiyProduct.form.description;

        vmDiyProduct.form.miniServer = productParam.miniServer ? productParam.miniServer : vmDiyProduct.form.miniServer;

        vmDiyProduct.form.paramShow = productParam.paramShow ? productParam.paramShow : vmDiyProduct.form.paramShow;
        vmDiyProduct.form.paramUrl = productParam.paramUrl ? productParam.paramUrl : vmDiyProduct.form.paramUrl;
        vmDiyProduct.form.paramWidth = productParam.paramWidth ? productParam.paramWidth : vmDiyProduct.form.paramWidth;
        vmDiyProduct.form.paramHeight = productParam.paramHeight ? productParam.paramHeight : vmDiyProduct.form.paramHeight;

        vmDiyProduct.form.paramUpdateUrl = productParam.paramUpdateUrl ? productParam.paramUpdateUrl : vmDiyProduct.form.paramUpdateUrl;
        vmDiyProduct.form.paramUpdateWidth = productParam.paramUpdateWidth ? productParam.paramUpdateWidth : vmDiyProduct.form.paramUpdateWidth;
        vmDiyProduct.form.paramUpdateHeight = productParam.paramUpdateHeight ? productParam.paramUpdateHeight : vmDiyProduct.form.paramUpdateHeight;

        vmDiyProduct.form.manageUrl = productParam.manageUrl ? productParam.manageUrl : vmDiyProduct.form.manageUrl;

        vmDiyProduct.form.syncOpen = productParam.syncOpen ? productParam.syncOpen : vmDiyProduct.form.syncOpen;
        vmDiyProduct.form.syncRenew = productParam.syncRenew ? productParam.syncRenew : vmDiyProduct.form.syncRenew;
        vmDiyProduct.form.syncUpdate = productParam.syncUpdate ? productParam.syncUpdate : vmDiyProduct.form.syncUpdate;
        vmDiyProduct.form.syncDelete = productParam.syncDelete ? productParam.syncDelete : vmDiyProduct.form.syncDelete;

        vmDiyProduct.form.saleType = productParam.saleType ? productParam.saleType : vmDiyProduct.form.saleType;


        if(vmDiyProduct.form.saleType == 1){
            //产品促销
            var priceItem=result.data.promotionList;
            if(priceItem!="" || priceItem.length>0){
                BaseForeach(priceItem,function(i,item){
                    var type='';
                    if(item.chargeId==1){
                        type="buy";
                    } else if(item.chargeId==2){
                        type="renew";
                    }

                    $("#chk_"+type+'_'+item.applyType+"_"+item.applyTime).attr("checked","checked");
                    $("#st_"+type+'_'+item.applyType+"_"+item.applyTime).val(item.saleType);
                    $("#txt_"+type+'_'+item.applyType+"_"+item.applyTime).val(item.saleValue);
                })
            }
        } else {
            chargeItemPrice(result.data);
        }
    }
}

//计费项价格
function chargeItemPrice(data){
    if(isNotNull(data.promotionList) || data.promotionList.length>0){
        BaseForeach(data.promotionList,function(i,item){
            //if(!isNotNull(item.regType)){
            var type="";
            if(item.chargeId==1){
                type="reg";
            } else if(item.chargeId==2){
                type="renew";
            }

            $("#txt_"+type+"_m_1_"+item.levelCode).val(item.price1);
            $("#txt_"+type+"_m_2_"+item.levelCode).val(item.price2);
            $("#txt_"+type+"_m_3_"+item.levelCode).val(item.price3);
            $("#txt_"+type+"_m_4_"+item.levelCode).val(item.price4);
            $("#txt_"+type+"_m_5_"+item.levelCode).val(item.price5);
            $("#txt_"+type+"_m_6_"+item.levelCode).val(item.price6);
            $("#txt_"+type+"_m_7_"+item.levelCode).val(item.price7);
            $("#txt_"+type+"_m_8_"+item.levelCode).val(item.price8);
            $("#txt_"+type+"_m_9_"+item.levelCode).val(item.price9);
            $("#txt_"+type+"_m_10_"+item.levelCode).val(item.price10);
            $("#txt_"+type+"_m_11_"+item.levelCode).val(item.price11);
            $("#txt_"+type+"_y_1_"+item.levelCode).val(item.pricey1);
            $("#txt_"+type+"_y_2_"+item.levelCode).val(item.pricey2);
            $("#txt_"+type+"_y_3_"+item.levelCode).val(item.pricey3);
            //}
        });
    }
}

//保存产品数据
function saveProductData(){
    var allParam = {
        productCode : productCode
    };

    var productName = $('#productName').val().trim();
    if ('' == productName) {
        topError(window, '请填写产品名称');
        return false;
    }
    allParam.productName = productName;

    //主参数值获取.
    allParam.productDetail = $('#productDetail').val();
    allParam.status = $('#status').val();
    allParam.price = $('#price').val();

    if (vmDiyProduct.form.paramShow == 'diy') {
        allParam.price = 0;
    }

    if (!IntegerUtils.isPositive(allParam.price) && vmDiyProduct.form.paramShow != 'diy') {
        topError(window, '价格必须为大于0的整数');
        return false;
    }
    allParam.buyMaxNum = $('#buyMaxNum').val();
    if (!IntegerUtils.isPositive(allParam.buyMaxNum)) {
        topError(window, '购买数量不正确，必须为大于0的整数');
        return false;
    }

    //element ui param.
    allParam = $.extend(allParam, vmDiyProduct.form);

    var productStr = JSON.stringify(allParam);

    //价格优惠
    var priceItemStr='';
    if(vmDiyProduct.form.saleType == 1){
        $("input[name=buyTime]:checked").each(function(){
            var priceItem={};
            priceItem.productCode=$("#hidProductCode").val();
            priceItem.chargeId=1;
            priceItem.applyTime=$(this).val();
            priceItem.applyType=$(this).attr("time");
            priceItem.saleType=$("#st_buy_"+$(this).attr("time")+"_"+$(this).val()).val();
            priceItem.saleValue=$("#txt_buy_"+$(this).attr("time")+"_"+$(this).val()).val();
            priceItemStr+=Commonjs.jsonToString(priceItem)+',';
        });

        $("input[name=renewTime]:checked").each(function(){
            var priceItem={};
            priceItem.productCode=$("#hidProductCode").val();
            priceItem.chargeId=2;
            priceItem.applyTime=$(this).val();
            priceItem.applyType=$(this).attr("time");
            priceItem.saleType=$("#st_renew_"+$(this).attr("time")+"_"+$(this).val()).val();
            priceItem.saleValue=$("#txt_renew_"+$(this).attr("time")+"_"+$(this).val()).val();
            priceItemStr+=Commonjs.jsonToString(priceItem)+',';
        });
    } else {
        BaseForeach(levelList,function(i,item){
            //注册
            var priceItem={};
            priceItem.chargeId=1;
            priceItem.levelCode=item.levelCode;
            priceItem.productCode=$("#hidProductCode").val();
            priceItem.price1=$("#txt_reg_m_1_"+item.levelCode).val();
            priceItem.price2=$("#txt_reg_m_2_"+item.levelCode).val();
            priceItem.price3=$("#txt_reg_m_3_"+item.levelCode).val();
            priceItem.price4=$("#txt_reg_m_4_"+item.levelCode).val();
            priceItem.price5=$("#txt_reg_m_5_"+item.levelCode).val();
            priceItem.price6=$("#txt_reg_m_6_"+item.levelCode).val();
            priceItem.price7=$("#txt_reg_m_7_"+item.levelCode).val();
            priceItem.price8=$("#txt_reg_m_8_"+item.levelCode).val();
            priceItem.price9=$("#txt_reg_m_9_"+item.levelCode).val();
            priceItem.price10=$("#txt_reg_m_10_"+item.levelCode).val();
            priceItem.price11=$("#txt_reg_m_11_"+item.levelCode).val();
            priceItem.pricey1=$("#txt_reg_y_1_"+item.levelCode).val();
            priceItem.pricey2=$("#txt_reg_y_2_"+item.levelCode).val();
            priceItem.pricey3=$("#txt_reg_y_3_"+item.levelCode).val();
            priceItemStr+=Commonjs.jsonToString(priceItem)+',';

            //续费
            priceItem={};
            priceItem.chargeId=2;
            priceItem.levelCode=item.levelCode;
            priceItem.productCode=$("#hidProductCode").val();
            priceItem.price1=$("#txt_renew_m_1_"+item.levelCode).val();
            priceItem.price2=$("#txt_renew_m_2_"+item.levelCode).val();
            priceItem.price3=$("#txt_renew_m_3_"+item.levelCode).val();
            priceItem.price4=$("#txt_renew_m_4_"+item.levelCode).val();
            priceItem.price5=$("#txt_renew_m_5_"+item.levelCode).val();
            priceItem.price6=$("#txt_renew_m_6_"+item.levelCode).val();
            priceItem.price7=$("#txt_renew_m_7_"+item.levelCode).val();
            priceItem.price8=$("#txt_renew_m_8_"+item.levelCode).val();
            priceItem.price9=$("#txt_renew_m_9_"+item.levelCode).val();
            priceItem.price10=$("#txt_renew_m_10_"+item.levelCode).val();
            priceItem.price11=$("#txt_renew_m_11_"+item.levelCode).val();
            priceItem.pricey1=$("#txt_renew_y_1_"+item.levelCode).val();
            priceItem.pricey2=$("#txt_renew_y_2_"+item.levelCode).val();
            priceItem.pricey3=$("#txt_renew_y_3_"+item.levelCode).val();
            priceItemStr+=Commonjs.jsonToString(priceItem)+',';
        });
    }
    priceItemStr=priceItemStr.substring(0, priceItemStr.length-1);

    var fn="saveDiyProductSet";
    var jsonStr='{"product":['+productStr+'],"priceItem":['+priceItemStr+']}';
    var params = Commonjs.getParams(fn,jsonStr,true);
    Commonjs.ajaxTrue(weburl,params,saveDataSuccess,true);
}

function saveDataSuccess(data){
    $.tooltip(data.msg,2000,true);
    $('html,body').scrollTop(0);
    window.location.reload();
    getDiyProduct();
}

var vmDiyProduct = new Vue({
    el: '#main-block',
    data: function() {
        return {
            iconOptions: [
                {label: '不显示', value: 'N'},
                {label: '显示', value: 'Y'}
            ],
            iconLocalOptions: [
                {label: '对齐到左边', value: 'left'},
                {label: '对齐到右边', value: 'right'},
                {label: '与中央对齐', value: 'middle'},
                {label: '与顶部对齐', value: 'top'},
                {label: '与底部对齐', value: 'bottom'}
            ],

            paramOptions: [
                {label: '默认（产品详细说明）', value: 'default'},
                {label: '自定义', value: 'diy'}
            ],

            saleTypeOptions: [
                {label: '使用会员折扣', value: 1},
                {label: '按会员等级设置', value: 2}
            ],

            miniServices: [],

            form: {
                productName: '',

                iconShow: 'N',
                iconUrl: '',
                iconWidth: 38,
                iconHeight: 38,
                iconLocal: 'middle',

                description: '',

                miniServer: '',
                paramShow: 'default',
                saleType: 1,
                paramUrl: '',
                paramWidth: 600,
                paramHeight: 400,
                paramUpdateUrl: '',
                paramUpdateWidth: 600,
                paramUpdateHeight: 400,
                manageUrl:'',
                syncOpen: 'Y',
                syncRenew: 'Y',
                syncUpdate: 'Y',
                syncDelete: 'Y'
            },
            uploadUrl: '',
            saleTypeShow: true
        }
    },
    methods: {
        /**
         * 上传成功.
         * @param rsp
         * @param file
         * @param fileList
         */
        uploadSuccess: function (rsp, file, fileList) {
            this.form.iconUrl = rsp.url;
            this.$refs['uploader'].clearFiles();
        },
        /**
         * 上传失败.
         * @param err
         * @param file
         * @param fileList
         */
        uploadError: function(err, file, fileList) {
            this.$message.error(err);
            this.$refs['uploader'].clearFiles();
        },
        /**
         * 上传失败.
         */
        paramShowChange: function() {
            var self = this;
            if(self.form.paramShow == "diy"){
                self.saleTypeShow = false;
                self.form.saleType = 1;
            } else {
                self.saleTypeShow = true;
            }
        },
        loadData: function () {
            var self = this;
            var service = {};
            var fn="mimiServiceSelect";
            service = Commonjs.jsonToString(service);
            var params = Commonjs.getParams(fn,service);
            Commonjs.ajaxSilence(weburl,params,true,function (data) {
                self.miniServices = data.data;
            }, function (data) {
                self.$message.error(data.msg);
            });
        }
    },
    mounted: function () {
        this.uploadUrl = realPath + '/upload.do';
        setTimeout(function () {
            $('input[type="file"]').css('display', 'none');
        }, 500);
        this.loadData();
    }
});